<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>群星网约车</title>
	<link rel="icon" href="../image/carMR.png" type="image/png">
	<!--这里引入页面的样式-->
	<style>
		.header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10px 20px;
			/* 			background-color:gainsboro; */
		}

		.logo {
			height: 50px;
		}

		.title {
			font-size: 24px;
			font-weight: bold;
		}

		.links {
			display: flex;
			align-items: center;
		}

		.links el-link {
			margin-left: 10px;
		}

		.user-info {
			display: flex;
			align-items: center;
		}

		.avatar {
			margin-right: 10px;
		}

		.username a {
			color: #333;
			text-decoration: none;
		}
		/* 绿色点样式 */
		.green-point {
		    width: 10px;
		    height: 10px;
		    background-color: green;
		    border-radius: 50%;
		    margin-right: 10px;
		    display: inline-block;
		}
		
		/* 红色点样式 */
		.red-point {
		    width: 10px;
		    height: 10px;
		    background-color: red;
		    border-radius: 50%;
		    margin-right: 10px;
		    display: inline-block;
		}
		/* 橘黄色点样式 */
		.orange-point {
		    width: 10px;
		    height: 10px;
		    background-color: orange;
		    border-radius: 50%;
		    margin-right: 10px;
		    display: inline-block;
		}
		.content {
			padding: 20px;
			text-align: center; /* 添加文本居中对齐 */
		}
		.map {
			height: 400px;
		}
		.order-dialog {
			margin: 0 auto; /* 水平居中对齐 */
		}

		.order-dialog .el-dialog__body {
			padding: 30px; /* 增加内边距 */
		}

		.order-info {
			margin-bottom: 20px;
		}

		.order-info p {
			margin: 5px 0;
		}

		.order-id-time {
			font-size: 16px;
			font-weight: bold;
		}

		.grid-container {
			display: grid;
			grid-template-columns: 1fr 1fr;
		}

		.grid-container div {
			margin-top: 10px;
			display: flex;
		}
		.grid-container strong {
			min-width: 80px;
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.button-group {
			display: flex;
			justify-content: center;
			margin-top: 20px;
		}
		.divider {
			border-top: 1px solid #000;
			margin: 10px 0;
		}
		#search-container {
			position: absolute;
			top: 70px;
			left: 16%;
			transform: translateX(-50%);
			width: 300px;
			z-index: 999;
			background: white;
			padding: 5px;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
			display: flex;
			gap: 10px;
		}
	</style>
	</head>
	<script src="../js/vue.js"></script>
	<script src="../element-ui/lib/index.js"></script>
	<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
	<script src="../js/axios-0.18.0.js"></script>
	<!-- 引入百度地图 API -->
	<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
	<script src="https://api.map.baidu.com/api?v=1.0&amp;type=webgl&amp;ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
	<body>
		<div id="app">
			<div class="header">
				<img class="logo" src="../image/carMR.png">
				<span class="title">群星网约车祝您一帆风顺</span>
				<div class="links">
					<el-link href="driverMain.html" target="_self" :underline="false">主页&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
					<el-link href="orderDriverInfo.html" target="_self" :underline="false">我的订单&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
					<el-link href="taxiInfo.html" target="_blank" :underline="false">群星简介&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
					<el-link href="driverInfo.html" target="_self" :underline="false">个人中心&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
					&nbsp;&nbsp;&nbsp;&nbsp;
					<div v-if="driverStatus === '在线'">
					    <div class="green-point"></div>
					</div>
					<div v-else-if="driverStatus === '离线'">
					    <div class="red-point"></div>
					</div>
					<div v-else>
					    <div class="orange-point"></div>
					</div>
					<el-select v-model="driverStatus" placeholder="选择司机状态" style="width: 120px;">
						<el-option label="离线" value="离线"></el-option>
						<el-option label="在线" value="在线"></el-option>
						<el-option label="接单中" value="接单中"></el-option>
					</el-select>
				</div>
				<div class="user-info">
					<div>
						<el-avatar :src="avatar"></el-avatar>
					</div>
					&nbsp;&nbsp;&nbsp;&nbsp;
					<span class="username"><a id="uname" href="javascript:void(0)">{{ displayUsername }}</a></span>
					&nbsp;&nbsp;&nbsp;&nbsp;
					<el-link target="_blank" :underline="false" @click="exitInfo">退出系统</el-link>
					&nbsp;&nbsp;&nbsp;&nbsp;
				</div>
			</div>
			<div class="content">
				<!-- 弹窗 -->
				<el-dialog :visible.sync="dialogVisible" title="订单详情" class="order-dialog">
					<div class="order-info">
						<p class="order-id-time"><strong>订单号：</strong>{{ orderDetails.orderId }}
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;				<strong>发起时间：</strong>{{ formatDateTime(orderDetails.startTime) }}
						</p>
						<div class="divider"></div>
						<div class="grid-container">
							<div><strong>起&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;点：</strong>{{ orderDetails.departureLocation }}</div>
							<div><strong>终&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;点：</strong>{{ orderDetails.destinationLocation }}</div>
							<div><strong>路&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;程：</strong>{{ orderDetails.distance }}</div>
							<div><strong>预计时间：</strong>{{ orderDetails.estimatedTime }}</div>
							<div><strong>用户编号：</strong>{{ orderDetails.uuserId }}</div>
							<div><strong>手机尾号：</strong>{{ formatPhoneNumber(orderDetails.phoneNumber) }}</div>
						</div>
					</div>
					<div class="button-group">
						<el-button @click="regectOrder" plain>拒单</el-button>
						<el-button @click="acceptOrder" type="primary" plain>接单</el-button>
					</div>
				</el-dialog>
				<div id="search-container">
					<el-input id="suggestId" v-model="locationInput" placeholder="请输入位置"></el-input>
					<el-button type="primary" @click="handleLocationSubmit">保存</el-button>
				</div>
				<el-main>
					<div id="allmap" class="map"></div>
				</el-main>
			</div>
			</div>
<script>
	// request拦截器，将用户token放入头中
	axios.interceptors.request.use(
			config => {
				let token = localStorage.getItem("token"); // 确保 token 正确存储在 localStorage 中
				if (token) {
					config.headers['token'] = token;
				}
				return config;
			},
			error => {
				console.log(error);
				return Promise.reject(error);
			}
	);
	new Vue({
		el: '#app',
		data() {
			return {
				map: null,
				dialogVisible: false,
				locationInput: '',
				local: null,
				autocomplete: null,
				userId: "",
				userName: "",
				driverStatus: '离线',
				websocket: null,
				avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 默认头像链接
				orderDetails: {
					orderId: '',
					departureLocation: '',
					destinationLocation: '',
					startTime: '',
					distance: '',
					estimatedTime: '',
					phoneNumber: '',
					uuserId: ''
				}
			};
		},
		created() {
/*			this.initWebSocket();*/
		},
		methods: {
			regectOrder(){
				this.dialogVisible = false;
				this.$message.success('拒单成功......');
			},
			acceptOrder(){
				axios.get('/order/orders/getOrderStatus?orderId='+this.orderDetails.orderId)
						.then(response => {
							if (response.data.code === 1) {
								console.log('可以接单继续执行了......');

								// 更新界面状态
								this.dialogVisible = false;
								this.driverStatus = '接单中';

								const data = {
									orderId: this.orderDetails.orderId,
									driverId: this.userId,
									userId: this.orderDetails.uuserId
								};

								// 接单请求
								axios.put('/order/orders/acceptOrder', data)
										.then(response => {
											if (response.data.code === 1) {
												this.$message.success('接单成功......');
												window.location.href = "driverTaxi.html";
											} else {
												this.errorMessage = response.data.msg;
												this.$message.error(this.errorMessage);
											}
										});

							} else {
								this.errorMessage = response.data.msg;
								this.$message.warning(this.errorMessage);
								return;
							}
						});
			},
			formatDateTime(dateTime) {
				const date = new Date(dateTime);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			formatPhoneNumber(phoneNumber) {
				if (!phoneNumber || phoneNumber.length < 11) {
					return phoneNumber;
				}
				const lastFourDigits = phoneNumber.slice(-4);
				return '*******' + lastFourDigits;
			},
			initWebSocket() {
					//let clientId = Math.random().toString(36).substr(2);
					console.log(this.userId + "098");
					const socketUrl = 'ws://localhost:10010/order/ws/' + this.userId.toString();
					if (typeof WebSocket === 'undefined') {
						this.$notify({
							title: '提示',
							message: '当前浏览器不支持 WebSocket，请使用最新版本的浏览器。',
							type: 'warning',
							duration: 0
						});
						return;
					}

					this.websocket = new WebSocket(socketUrl);

					this.websocket.onopen = () => {
						console.log('WebSocket 已连接');
					};

					this.websocket.onmessage = (msg) => {
						console.log('收到消息：', msg.data);
						const data = JSON.parse(msg.data);
						this.handleWebSocketMessage(data);
					};

					this.websocket.onerror = (error) => {
						console.error('WebSocket 错误：', error);
						this.$notify({
							title: '错误',
							message: 'WebSocket 连接错误，请检查服务器状态。',
							type: 'error',
							duration: 0
						});
					};

					this.websocket.onclose = () => {
						console.log('WebSocket 已关闭');
					};
			},
			handleWebSocketMessage(data) {
				const audio = new Audio('../video/driver.mp3');
				audio.play();
				this.$notify({
					title: data.type === 1 ? '新订单提醒' : '催单提醒',
					message: '订单编号：'+data.orderId+ ' 来单位置：' +data.departureLocation,
					type: 'info',
					duration: 0,
					onClick: () => {
						// 点击通知后的操作，例如跳转到订单详情页
						console.log('通知被点击');
						this.showOrderDetails(data);
					}
				});
			},
			showOrderDetails(data) {
				// 假设 data 包含完整的订单信息，如果不包含，需要额外的请求获取详细信息
				this.orderDetails = {
					orderId: data.orderId,
					departureLocation: data.departureLocation,
					destinationLocation: data.destinationLocation,
					startTime: data.startTime,
					distance: data.distance,
					estimatedTime: data.estimatedTime,
					phoneNumber: data.phoneNumber,
					uuserId: data.uuserId
				};
				this.dialogVisible = true;
				localStorage.setItem("orderId",this.orderDetails.orderId);
				localStorage.setItem("departureLocation",this.orderDetails.departureLocation)
				localStorage.setItem("destinationLocation",this.orderDetails.destinationLocation)
			},
			initMap() {
				// 百度地图API功能
				this.map = new BMap.Map("allmap");
				var point = new BMap.Point(116.331398, 39.897445);
				this.map.centerAndZoom(point, 12);
				// 启用滚轮缩放功能
				this.map.enableScrollWheelZoom(true);
				// 添加放大缩小控件
				this.map.addControl(new BMap.NavigationControl());
				// 添加搜索功能
				this.local = new BMap.LocalSearch(this.map, {
					renderOptions: {
						map: this.map
					}
				});
				axios.get("/driver/driver-locations/locationById?driverId="+this.userId)
				.then(response=>{
					if(response.data.code==1){
						console.log("获取定位成功");
						var locationName = response.data.data;
						this.local.search(locationName);
					}else {
						this.$message({
							message: response.data.msg,
							type: 'warning'
						});
					}
				});
				// 在地图初始化完成后再初始化自动补全功能
				this.$nextTick(() => {
					this.initAutocomplete();
				});
			},
			initAutocomplete() {
				if (this.map) {
					this.autocomplete = new BMap.Autocomplete({
						"input": "suggestId",
						"location": this.map // 使用Vue实例的map变量
					});

					this.autocomplete.addEventListener("onconfirm", (e) => {
						var _value = e.item.value;
						this.locationInput = _value.province + _value.city + _value.district + _value.street + _value.business;
					});
				} else {
					console.error("Map is not initialized.");
				}
			},
			handleLocationSubmit() {
				if (!this.locationInput) {
					this.$message({
						message: '请输入位置',
						type: 'warning'
					});
					return;
				}

				// 先移除之前的回调函数
				this.local.setSearchCompleteCallback(null);

				this.local.search(this.locationInput);
				this.local.setSearchCompleteCallback(() => {
					var results = this.local.getResults();
					if (!results || results.getCurrentNumPois() === 0) {
						this.$message({
							message: '请输入正确的地点名',
							type: 'warning'
						});
						return;
					}

					// 发送添加位置请求
					axios.post("/driver/driver-locations/addLocation", {
						driverId: this.userId,
						location: this.locationInput
					}).then(response => {
						if (response.data.code == 1) {
							this.$message({
								message: '位置添加成功',
								type: 'success'
							});
							var locationName = response.data.data;
							this.local.search(locationName);
						} else {
							this.$message({
								message: '位置添加失败，请重试',
								type: 'error'
							});
						}
						// 清空输入框内容
						this.locationInput = '';
						// 清理当前的回调函数，避免重复设置
						this.local.setSearchCompleteCallback(null);
					});
				});
			},
			orderInfo(){

			},
			exitInfo(){
			axios.put("/driver/drivers/exitStatus?driverId="+this.userId)
					.then(response=>{
						if(response.data.code==1){
							console.log("退出修改状态成功");
						}
					});
				localStorage.removeItem('userId');
				localStorage.removeItem('userName');
				window.location.href = "../html/login.html"; // 页面跳转
			},
			// 发送请求给后端更新司机状态
			updateDriverStatus(status) {
				localStorage.setItem("driverStatus",this.driverStatus);
				axios.put('/driver/drivers/updateDriverStatus', {
					id: this.userId,
					status: status
				})
				.then(response => {
					console.log('更新司机状态成功:', response.data);
				})
				.catch(error => {
					console.error('更新司机状态失败:', error);
				});
			},
			// 监听司机状态变化
			onDriverStatusChange() {
				console.log('司机状态变为：', this.driverStatus);
				// 根据不同的司机状态发送请求给后端
				switch (this.driverStatus) {
					case '离线':
						// 发送请求告诉后端司机已经离线
						this.updateDriverStatus('3');
						break;
					case '在线':
						// 发送请求告诉后端司机已经上线
						this.updateDriverStatus('1');
						break;
					case '接单中':
						// 发送请求告诉后端司机正在接单
						this.updateDriverStatus('2');
						break;
					default:
						console.error('未知司机状态:', this.driverStatus);
						break;
				}
			},
		},
		mounted() {
			var id=localStorage.getItem('userId');
			this.userId = parseInt(id, 10);
			this.userName = localStorage.getItem('userName');
			this.avatar = localStorage.getItem('pic');
			this.initWebSocket();
			this.updateDriverStatus('3');
/*			 if (this.userName === null) {
			 	this.$message.error('非法进入,请先登录');
			 	setTimeout(() => {
			 		window.location.href = "../html/login.html";
			 	}, 3000); // 延迟2秒（2000毫秒）执行
			 } else {
			 	this.initMap();
			 }*/
			this.initMap();
		},
		computed: {
			displayUsername() {
				// 如果 userName 不为空，显示 userName；否则显示 "未登录"
				return this.userName ? this.userName : "未登录";
			}
		},
		watch: {
		    // 监听司机状态变化
		    driverStatus: 'onDriverStatusChange'
		},
		beforeDestroy() {
			if (this.websocket) {
				this.websocket.close();
			}
		}
	});
</script>
<!-- 不用vue的js代码写在下面-->
<script>
</script>
</body>
</html>
